<template>
  <div class="log-item">
    <div class="main">
      <div class="user">
        <XrAvatar v-if="data.createUser"
                  :name="data.createUser.realname"
                  :id="data.createUser.userId"
                  :size="38"
                  :src="data.createUser.img"
                  :disabled="false"
                  class="user-img"/>
        <div class="box">
          <div class="username">
            {{ data.realname }}
          </div>
          <div class="time">
            创建日志于 {{ data.createTime }} <!--{{ data.isRead === 1 ? '已读' : '未读' }}-->
          </div>
          <div class="handle">
            <el-button v-if="showHistoryBtn" link @click="checkHistoryClick">
              查看以往日志
            </el-button>
          </div>
          <div class="comment-status">
            <span class="icon wk wk-task"/>
            <span>{{ getCategory(data.categoryId) }}-{{ data.replyNum === 0 ? '未点评' : '已点评' }}</span>
            <span :class="{active: data.replyNum !== 0}" class="dot"/>
          </div>
        </div>
      </div>
      <div class="content">
        <div v-if="data.content" class="content-box">
          <div class="content-title">
            {{ logTitleName }}：
          </div>
          <div class="content-text">{{ data.content }}</div>
        </div>
        <div v-if="data.tomorrow" class="content-box">
          <div class="content-title">
            {{ logNextTitleName }}：
          </div>
          <div class="content-text">{{ data.tomorrow }}</div>
        </div>
        <div v-if="data.question" class="content-box">
          <div class="content-title">
            遇到的问题：
          </div>
          <div class="content-text">{{ data.question }}</div>
        </div>
      </div>

      <PictureListView v-if="data.img && data.img.length !== 0" :list="data.img"/>
      <FileListView v-if="data.file && data.file.length !== 0" :list="data.file"/>
      <RelatedBusinessList v-if="allDataLen > 0" :data="allData" @select="relatedClick"/>
      <div v-if="data.getBulletin" class="content">
        <div class="content-box">
          <div class="content-title"> 销售简报</div>
          <div class="content-text">
            <ReportMenu :list="reportList" @select="reportSelect"/>
          </div>
        </div>
      </div>

      <flexbox
          v-if="(data.sendUserList && data.sendUserList.length > 0) || (data.sendDeptList && data.sendDeptList.length > 0)"
          class="send-list">
        <span class="send-list__label">发送给：</span>
        <template v-for="(item, index) in (data.sendUserList || []).concat(data.sendDeptList || [])"
                  :key="index">
          <span class="send-list__user">
          <XrAvatar :name="item.realname || item.name"
                    :id="item.userId"
                    :size="32"
                    :src="item.img"
                    :disabled="false"/>
        </span>
        </template>

      </flexbox>
    </div>

    <div class="footer">
      <div style="flex: 1;">
        <FavList :is-favour="data.isFavour" :data="data.favourUser" @fav="favourClick"/>
      </div>
      <el-dropdown v-if="data.permission && (data.permission.isUpdate || data.permission.isDelete)"
                   trigger="click" @command="handleCommand">
        <el-button icon="el-icon-more" class="more"/>
        <template v-slot:dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-if="data.permission.isUpdate" command="edit">编辑</el-dropdown-item>
            <el-dropdown-item v-if="data.permission.isDelete" command="delete">删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>

      </el-dropdown>
      <!--      icon="wk wk-good"-->
      <el-button ref="favBtnRef" :type="data.isFavour ? 'primary' : ''"
                 style="margin-left: 10px;"
                 class="fav-btn"
                 @click="favourClick">赞{{ `${data.favourUser.length > 0 ? `(${data.favourUser.length})` : ''}` }}
      </el-button>
      <!--      icon="wk wk-message"-->
      <el-button type="primary" class="replay-btn"
                 @click="replayClick">{{ '评论' + (replyTotal > 0 ? `(${replyTotal})` : '') }}
      </el-button>
    </div>
    <div v-if="showReply" class="reply-wrapper">
      <reply-comment v-loading="commentLoading" ref="f_reply"
                     @toggle="closeOtherReply"
                     @reply="handleReply"/>
      <comment-list v-if="replyList.length > 0" ref="comment_list"
                    :id="data.logId" :list="replyList"
                    type="2"
                    @delete="deleteComment"
                    @close-other-reply="$refs.f_reply.toggleFocus(true)"/>
    </div>
  </div>
</template>

<script setup>
import PictureListView from '/src/szcomponent/PictureListView'
import FileListView from '/src/szcomponent/FileListView'
import {useNumberHook} from "@/hooks/useNumberHook.js";
import ReplyComment from '/src/components/ReplyComment'
import RelatedBusinessList from '/src/components/RelatedBusinessList'
import CommentList from '/src/components/CommentList'
import ReportMenu from './ReportMenu.vue'
import FavList from './FavList.vue'
import {journalDeleteAPI, journalSetReadAPI, oaLogFavourOrCancelAPI} from "@/api/oa/journal.js";
import {queryCommentListAPI, setCommentAPI} from "@/api/oa/common.js";
import {useUserStore} from "@/store/modules/user.js";


const {separator} = useNumberHook();

defineOptions({
  name: 'LogItem',
})

const props = defineProps({
  data: {
    type: Object,
    required: true
  },
  index: {
    type: Number,
    default: 0
  },
  showHistoryBtn: {
    type: Boolean,
    default: false
  }
})

const optionData = reactive({
  isWaiting: false,
  showReply: false,
  commentLoading: false,
  replyList: [],

  // 简报信息
  reportList: [{
    type: 'customer',
    key: 'customerCount',
    info: '今日新增客户',
    name: '今日新增客户 0'
  }, {
    type: 'business',
    key: 'businessCount',
    info: '今日新增商机',
    name: '今日新增商机 0'
  }, {
    type: 'contract',
    key: 'contractCount',
    info: '今日新增合同',
    name: '今日新增合同 0'
  }, {
    type: 'receivables',
    key: 'receivablesMoney',
    info: '今日新增回款',
    name: '今日新增回款 0'
  }, {
    type: 'record',
    key: 'recordCount',
    info: '今日新增跟进记录',
    name: '今日新增跟进记录 0'
  }]
})

const {isWaiting, showReply, commentLoading, replyList, reportList} = toRefs(optionData)

const emits = defineEmits(['delete', 'edit', 'read', 'relate-detail', 'report-detail', 'check-history'])

const userInfo = computed(() => {
  // const erpUserStore = useErpUserStore();
  const erpUserStore = useUserStore();

  return erpUserStore.userInfo
})

const allData = computed(() => {
  return {
    business: props.data ? props.data.businessList : [],
    contacts: props.data ? props.data.contactsList : [],
    contract: props.data ? props.data.contractList : [],
    customer: props.data ? props.data.customerList : []
  }
})


const allDataLen = computed(() => {
  let res = 0
  if (!props.data) return res
  const keys = ['businessList', 'contactsList', 'contractList', 'customerList']
  keys.forEach(key => {
    res += props.data[key].length || 0
  })
  return res
})
const replyTotal = computed(() => {
  let num = 0
  optionData.replyList.forEach(item => {
    num++
    num += item.childCommentList.length || 0
  })
  return num || props.data.replyNum
})
// 日志标题
const logTitleName = computed(() => {
  return {
    1: '今日',
    2: '本周',
    3: '本月'
  }[props.data.categoryId] + '工作内容'
})
const logNextTitleName = computed(() => {
  return {
    1: '明日',
    2: '下周',
    3: '下月'
  }[props.data.categoryId] + '工作内容'
})


function created() {
  // this.$nextTick(() => {
  //   if (this.data.isRead === 1) return
  //   this.$bus.on('load-more-work-log', clientHeight => {
  //     if (this.isWaiting) return
  //     if (this.calcVisible(clientHeight)) {
  //       this.isWaiting = true
  //       setTimeout(() => {
  //         this.isWaiting = false
  //         if (this.calcVisible(clientHeight)) {
  //           this.readLog()
  //         }
  //       }, 3000)
  //     }
  //   })
  // })

  if (props.data.getBulletin) {
    const data = props.data.bulletin || {}
    optionData.reportList = optionData.reportList.map(item => {
      if (item.key == 'receivablesMoney') {
        data.receivablesMoney = separator(Math.floor(data.receivablesMoney || 0))
      }
      item.name = `${item.info} ${data[item.key]}`
      return item
    })
  }
}

created()


function getCategory(categoryId) {
  const map = {
    1: '日报',
    2: '周报',
    3: '月报'
  }
  return map[categoryId]
}

/**
 * 编辑/删除
 * @param action
 * @param index
 */
function handleCommand(action, index) {
  if (action === 'delete') {
    ElMessageBox.confirm('确定删除?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      journalDeleteAPI({logId: props.data.logId}).then(() => {
        ElMessage.success({message: '删除成功!'})
        emits('delete', index)
      })
    }).catch(() => {
      ElMessage.info({message: '已取消删除'})
    })
  } else {
    emits('edit', props.index, props.data)
  }
}

/**
 * 判断当前组件是否完全可见
 */
function calcVisible(boxHeight) {
  if (props.data.isRead === 1) return false
  const domRect = this.$el.getBoundingClientRect()
  return boxHeight > (domRect.top + domRect.height)
}

/**
 * 日志标记为已读
 */
function readLog() {
  if (props.data.isRead === 1) return
  emits('read')
  journalSetReadAPI({
    logId: props.data.logId
  }).then(() => {
    this.$bus.off('load-more-work-log')
  }).catch()
}

/**
 * 日志评论
 */
function handleReply(data) {
  optionData.commentLoading = true
  setCommentAPI({
    type: 2,
    content: data,
    typeId: props.data.logId
  }).then(res => {
    res.data.user = {
      userId: userInfo.value.userId,
      realname: userInfo.value.realname,
      img: userInfo.value.img
    }
    res.data.childCommentList = []
    // this.$emit('add-comment', {
    //   data: res.data,
    //   index: this.index
    // })
    optionData.replyList.push(res.data)
    optionData.commentLoading = false
    optionData.showReply = false
    nextTick(() => {
      optionData.showReply = true
    })
  }).catch(() => {
    optionData.commentLoading = false
  })
}

function deleteComment(index) {
  optionData.replyList.splice(index, 1)
}

function closeOtherReply(flag) {
  if (!flag && this.$refs.comment_list) {
    this.$refs.comment_list.closeReply()
  }
}

/**
 * 相关信息点击
 */
function relatedClick(type, data) {
  emits('relate-detail', type, data)
}

/**
 * 回复点击
 */
function replayClick() {
  optionData.showReply = !optionData.showReply
  if (optionData.replyList.length == 0) {
    getCommentList()
  }
}

/**
 * 获取回复列表
 */
function getCommentList() {
  queryCommentListAPI({
    typeId: props.data.logId,
    type: 2 // 任务1 日志2
  }).then(res => {
    const list = res.data.data || []
    optionData.replyList = list
    // this.replyList = list.sort((a, b) => {
    //   return new Date(b.createTime) - new Date(a.createTime)
    // }) || []
  }).catch(() => {
  })
}

/**
 * 简报详情
 */
function reportSelect(item) {
  emits('report-detail', item, props.data)
}

/**
 * 查看历史
 */
function checkHistoryClick() {
  emits('check-history', props.data.createUser)
}

/**
 * 点赞
 */
const favBtnRef = ref()

function favourClick() {
  console.log("favourClick")
  // this.$refs.favBtn.$el.blur()
  oaLogFavourOrCancelAPI({
    isFavour: !props.data.isFavour,
    logId: props.data.logId
  }).then(res => {
    console.log("resData", res.data)
    const resData = res.data.data || {}
    props.data.isFavour = resData.isFavour
    props.data.favourUser = resData.favourUser
  }).catch((e) => {
    console.log("e", e)
  })
}
</script>

<style scoped lang="scss">
.log-item {
  .main {
    .user {
      color: #333;
      font-size: 14px;
      padding: 10px 15px 5px;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .user-img {
        margin-right: 12px;
      }

      .box {
        height: auto;
        flex: 1;
        margin-top: -10px;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .username {
          margin-right: 15px;
        }

        .time {
          font-size: 12px;
          color: #999;
        }

        .handle {
          flex: 1;
          margin-left: 30px;

          .el-button {
            font-size: 12px;
          }
        }

        .comment-status {
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;

          .icon {
            font-size: 14px;
            color: #2772FF;
            margin-right: 5px;
          }

          .dot {
            width: 7px;
            height: 7px;
            background-color: #F95A5A;
            border-radius: 50%;
            margin-left: 5px;
            display: inline-block;

            &.active {
              background-color: #4ca824;
            }
          }
        }
      }
    }

    .content {
      margin: 0 15px 0 68px;

      .content-box {
        font-size: 13px;
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 15px;
        }

        .content-title {
          /*color: #999;*/
          color: #333;
          font-weight: bold;
          margin-bottom: 10px;
        }

        .content-text {
          line-height: 1.5;
          white-space: pre-wrap;
          word-wrap: break-word;
        }
      }
    }

    .picture-list-view {
      margin: 0 15px 10px 68px;
    }

    .file-list-view {
      width: 800px;
      margin: 0 15px 10px 68px;
    }

    .related-business-list {
      width: 800px;
      margin: 0 15px 10px 68px;
    }

    .comment-list {
      padding: 10px 30px 10px 60px;
      border-top: 1px solid #e6e6e6;
    }
  }

  .footer {
    width: 100%;
    height: 38px;
    background-color: #F4F7FF;
    padding: 0 15px;
    display: flex;
    align-items: center;

    .fav-btn,
    .replay-btn {
      :deep( i) {
        margin-right: 5px;
        font-size: 14px;
      }
    }

    .el-button {
      padding: 6px 10px;
    }
  }

  .reply-wrapper {
    border-top: 1px solid #e6e6e6;
    padding: 20px 20px 10px;
    background-color: #f9f9f9;
  }
}

.send-list {
  padding: 8px 15px 8px 68px;

  &__label {
    color: #333;
    font-size: 12px;
  }

  &__user {
    position: relative;
    display: inline-block;
  }

  &__user + &__user {
    margin-left: 7px;
  }
}
</style>
